import { DownOutlined, PlusOutlined, InfoCircleOutlined} from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button,  Dropdown, Menu,Card, Table, Row, Col, Tooltip, Radio,Input,message,Checkbox,Descriptions} from 'antd';
import { formatMessage,FormattedMessage } from 'umi-plugin-react/locale';
import React, { useState, useRef, useEffect } from 'react';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import DataForm from './components/DataForm';
import { selectToLabel } from '@/utils/utils';
import { TableListItem } from './data.d';
import { queryRule, updateRule, addRule, removeRule,queryCodeRule,updateTemplateRule } from './service';
import router from "umi/router";

import * as RequestHelper from '@/helpers/RequestHelper';
import PreviewForm from '@/components/PreviewForm';
import { FormValueType } from '@/pages/crm/depart/components/UpdateForm';
import * as TsxHelper from '@/helpers/TsxHelper';
import styles from "./style.less";
interface TableListProps extends FormComponentProps {}

const FormItem = Form.Item;
const { TextArea } = Input;
const TableList: React.FC<TableListProps> = (props:any) => {
    // 初始化变量区
    // 维护API状态数据
    const [apiState, setApiState] = useState<any>({common:{}});
    // 是否更新 关键变量
    const [isUpdate, setIsUpdate] = useState<boolean>(false);
    // 表单可见 关键变量
    const [dataModalVisible, handleDataModalVisible] = useState<boolean>(false);
    // 图片预览
    const [previewModelVisible, handlePreviewModalVisible] = useState<boolean>(false);
    const [previewImg, setPreviewImg] = useState('');
    // 表单数据
    const [dataFormValues, setDataFormValues] = useState<any>({});
    // 选中的记录
    const [rowKeys, setRowKeys] = useState<string[]|number[]>([]);
    const [emailList, setEmailList] = useState<any>([]);
    const [smsList, setSmsList] = useState<any>([]);
    const [common, setCommon] = useState<any>();
    const [checkBoxList, setCheckBoxList] = useState<any>([]);

    const actionRef = useRef<ActionType>();

    const { form , location } = props;

    useEffect(()=>{
        var params = {
            id: location.query.id
        }
        queryCodeRule(params).then(res=>{
            if(res.code == 0){
                setCommon(res.data.common);
                if(res.data.list && res.data.list.length>0){
                    setDataFormValues(res.data.list[0]);
                    setEmailList(res.data.list[0].newEmailArr);
                    setSmsList(res.data.list[0].newSmsArr);
                    let arr = []
                    if(res.data.list[0].emailStatus == true){
                        arr.push(2);
                    }
                    if(res.data.list[0].smsStatus == true){
                        arr.push(3);
                    }
                    setCheckBoxList(arr);
                }
                
            }
        })
    },[])

    // 列定义
    const columns = [
        {
            title: '语言标签',
            dataIndex: 'langTag',
            width:200,
        },
        {
            title: '语言描述',
            dataIndex: 'text',
            width:250,
        },
        {
            title: '通知标题',
            dataIndex: 'title',
            render:(value:any,record:any,index:any) => (
                <Input defaultValue={value} onChange={(e)=>{setEmailValue('title',e.target.value,index)}}/>
            )
        },
        {
            title: '通知内容',
            dataIndex: 'content',
            render:(value:any,record:any,index:any) => (
                <TextArea rows={2} defaultValue={value} onChange={(e)=>{setEmailValue('content',e.target.value,index)}}/>
            )
        }
    ];

    const smsColumns = [
        {
            title: '语言标签',
            dataIndex: 'langTag',
            width:200,
        },
        {
            title: '语言描述',
            dataIndex: 'text',
            width:250,
        },
        {
            title: '模板ID',
            dataIndex: 'templateCode',
            width: 200,
            render:(value:any,record:any,index:any) => (
                <Input defaultValue={value} onChange={(e)=>{setSmsValue('templateCode',e.target.value,index)}}/>
            )
        },
        {
            title: '验证码变量名',
            dataIndex: 'codeParam',
            render:(value:any,record:any,index:any) => (
                <Input defaultValue={value} onChange={(e)=>{setSmsValue('codeParam',e.target.value,index)}}/>
            )
        },
        {
            title: '短信签名名称',
            dataIndex: 'signName',
            render:(value:any,record:any,index:any) => (
                <Input defaultValue={value} onChange={(e)=>{setSmsValue('signName',e.target.value,index)}}/>
            )
        }
    ];

    const setEmailValue = (name,value,index) => {
        let list = emailList;
        list[index][name] = value;
        console.log(list);
        setEmailList(list);
    }

    const setSmsValue = (name,value,index) => {
        let list = smsList;
        list[index][name] = value;
        console.log(list);
        setSmsList(list);
    }

    // 请求接口数据, 设置组件状态
    const getTableData = (params:any) => {
        return queryRule(params).then((res:any) => {
            setApiState(res.data)
            return res.data.listData
        })
    }

    const okHandle = () => {
        form.validateFields((err, fieldsValue) => {
          if (err) return;
          
          console.log("submit fields ", fieldsValue)
          var email = [];
          if(emailList && emailList.length > 0){
            emailList.map((item:any,index:any)=>{
                email.push({
                    langTag: item.langTag,
                    title: item.title,
                    content: item.content,
                })
            })
          }
          var sms = [];
          if(smsList && smsList.length > 0){
            smsList.map((item:any,index:any)=>{
                sms.push({
                    langTag: item.langTag,
                    templateCode: item.templateCode,
                    codeParam: item.codeParam,
                    signName: item.signName,
                })
            })
          }
          var submitValue = {
              id: location.query.id,
              smsStatus: fieldsValue.channel.indexOf(3) > -1 ? true : false,
              emailStatus: fieldsValue.channel.indexOf(2) > -1 ? true : false,
              emailTemplate: JSON.stringify(email),
              smsTemplate: JSON.stringify(sms),
          }
          // 如果更新成功之后，重置表单
          updateTemplateRule(submitValue).then((res:any) => {
            if(res.code == 0){
              message.success('保存成功')
              router.push(`/system/sms-setting/code`);
            }
          })
    
        });
      };

      const contentDes = (
          <div>{dataFormValues.description_url ? <span>{formatMessage({ id: dataFormValues.description_url })}</span>:''}</div>
      );

    return (
        <PageHeaderWrapper style={{backgroundColor:"#fff"}}
            content={contentDes}
        >
          <div style={{padding:"10px"}}>
            <Card title="" bordered={false}>
                {/* <Descriptions column={5} title="模板信息">
                    <Descriptions.Item label="模板编号">{dataFormValues.key}</Descriptions.Item>
                    <Descriptions.Item label={dataFormValues.description_url ? <span>{formatMessage({ id: dataFormValues.description_url })}</span>:''}>{}</Descriptions.Item>
                </Descriptions> */}
            <Row>
                <Col span={12}> 
                    <FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 20 }}
                        label={
                          <span>
                            <FormattedMessage id="支持方式" />
                            <em className={styles.optional}>
                              <Tooltip title={<FormattedMessage id="若没勾选，则下面不显示对应的方式。" />}>
                                <InfoCircleOutlined style={{ marginRight: 4,marginLeft: 4 }} />
                              </Tooltip>
                            </em>
                          </span>
                        }>
                          {form.getFieldDecorator('channel', {
                            initialValue: [dataFormValues.emailStatus == true ? 2:'', dataFormValues.smsStatus == true ? 3:''],
                            // rules: [{ required: true, message: '请选择渠道'}],
                          })(<Checkbox.Group onChange={(list)=>{console.log(list);setCheckBoxList(list)}}>
                            {
                                common?.channel && common?.channel.length>0 && common.channel.map((item:any)=>{
                                    return <Checkbox value={item.value}>{item.name}</Checkbox>
                                })
                            }
                            
                        </Checkbox.Group>)}
                    </FormItem>
                </Col>
            </Row>
            </Card>
            {(checkBoxList.indexOf(2) > -1) &&
            <Card title="邮箱模板配置" bordered={false}>
                <Row>
                    <Col span={24}>
                        <Table
                            columns={columns}
                            pagination={false}
                            dataSource={emailList}
                        />
                    </Col>
                </Row>
            </Card>
            }
            
            {(checkBoxList.indexOf(3) > -1) &&
            <Card title="短信模板配置" bordered={false}>
                <Row>
                    <Col span={24}>
                        <Table
                            columns={smsColumns}
                            pagination={false}
                            dataSource={smsList}
                        />
                    </Col>
                </Row>
            </Card>
            }
            <Button type="primary" style={{margin:"10px 20px"}} onClick={()=>{okHandle()}}>保存</Button>
          </div>
        </PageHeaderWrapper>
    );
};

/**
* 添加节点
* @param fields
*/
const handleAdd = async (fields: any) => {
    return RequestHelper.bdExec({
        fn: addRule,
        args: fields,
        successMsg: formatMessage({ id: 'app.base.store-success' }),
        failMsg: formatMessage({ id: 'app.base.api-exception' }),
    });
};

/**
* 更新节点
* @param fields
*/
const handleUpdate = async (fields: FormValueType) => {
    return RequestHelper.bdExec({
        fn: updateRule,
        args: fields,
        successMsg: formatMessage({ id: 'app.base.update-success' }),
        failMsg:  formatMessage({ id: 'app.base.api-exception' }),
    });
};

// @ts-ignore
/**
 *  删除节点
 */
const handleRemove = async (selectedRows: TableListItem[]) => {
    if (!selectedRows) return true;
    const ids:any = selectedRows.map(row => row.id).toString();
    return RequestHelper.bdExec({
        fn: removeRule,
        args: {ids},
        successMsg: formatMessage({ id: 'app.base.destroy-success' }),
        failMsg:  formatMessage({ id: 'app.base.api-exception' }),
        hasLoading: false
    });
};


export default Form.create<TableListProps>()(TableList);
